import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/user.dart';

class UserService {
  final dbHelper = DatabaseHelper.instance;

  Future<int> insertUser(User user) async {
    Database db = await dbHelper.database;
    return await db.insert('users', user.toMap());
  }

  Future<User?> getUserByUsername(String username) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'users',
      where: 'username = ?',
      whereArgs: [username],
    );

    if (maps.isNotEmpty) {
      return User.fromMap(maps.first);
    }
    return null;
  }

  Future<User?> getUserById(int id) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'users',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return User.fromMap(maps.first);
    }
    return null;
  }

  Future<List<User>> getAllUsers() async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query('users');
    return List.generate(maps.length, (i) => User.fromMap(maps[i]));
  }

  Future<bool> authenticate(String username, String password) async {
    User? user = await getUserByUsername(username);
    if (user != null && user.password == password) {
      return true;
    }
    return false;
  }

  Future<bool> isAdmin(String username) async {
    User? user = await getUserByUsername(username);
    return user != null && user.isAdmin;
  }
}
